<?php
use yii\helpers\Html;
use app\models\Content;
use app\models\ContentSearch;
use app\models\ContentCategory;
use app\models\ContentAttrRelationships;
// use common\component\tool\Tool;
use common\component\tool\Pages;
use yii\db\Expression;

/*内容列表*/
function smarty_block_content($params, $content, Smarty_Internal_Template $template, &$repeat)
{
    // P($params);
    $app_id = Yii::$app->params['app_id'];

    if(isset($_GET['page'])){
        $currPage = intval($_GET['page']?$_GET['page']:1);
    }else{
        $currPage = 1;
    }
    // $pageSize = Tool::getPageSize();
    $pageSize = isset($params['pageSize'])?intval($params['pageSize']):Yii::$app->params['maxPageSize'];
    if($pageSize > Yii::$app->params['maxPageSize']){//最大50，防止传大数字
        $pageSize = Yii::$app->params['maxPageSize'];
    }
    // P($_GET);
    if(isset($_GET['key'])){
    	$params['title'] = $_GET['key'];
    }


    /*排序*/
    $sort = [
            'istop' => SORT_DESC,
            'toptime' => SORT_DESC,
            '{{%content}}.sort' => SORT_DESC,
            'add_time' => SORT_DESC
        ];
    if(isset($params['sort']) and $params['sort'] == 'asc'){
        $sort = [
                'istop' => SORT_DESC,
                'toptime' => SORT_DESC,
                '{{%content}}.sort' => SORT_ASC,
                'add_time' => SORT_ASC
            ];
    }
    // P($sort);

    /*
    如果参数中存在catid，直接调取此类目的内容，
    如果参数中有category，需要根据category，取出catid
    如果两个都存在，则忽略category
    */
    if(isset($params['category'])){
        $res = ContentCategory::find()->select(['catid'])
                    ->where('alias = :alias', [':alias' => $params['category']])
                    ->asArray()->one();
        if(!is_null($res)){
            $params['catid'] = $res['catid'];
        }
    }


    // P($params);
    $search = (new ContentSearch())->search($params, $app_id);
    if($search === false){//验证搜索参数不通过
        $count = 0;
        $contentList = array();
    }else{
        $count = $search->count();
        if(isset($params['flag'])){
            $contentList = $search->select(['content_id', 'title', 'titlecolor', '{{%content}}.catid', '{{%content}}.preview', '{{%content}}.outside', '{{%content}}.url_target', '{{%content}}.outside_url', 'source', 'author', 'keyword', 'describe', 'content', 'pc_preview_count', 'mobile_preview_count', 'add_time'])
                  ->andWhere('state = 3 and {{%content}}.display = 2')
                  ->andWhere(new Expression("FIND_IN_SET(:flag, {{%content}}.flag)", [":flag"=>$params['flag']]))
                  ->joinWith('category')
                  ->offset($pageSize*($currPage-1))->limit($pageSize)
                  ->orderBy($sort)
              // ->createCommand()->getRawSql();
              ->asArray()->all();
        }else{
            $contentList = $search->select(['content_id', 'title', 'titlecolor', '{{%content}}.catid', '{{%content}}.preview', '{{%content}}.outside', '{{%content}}.url_target', '{{%content}}.outside_url', 'source', 'author', 'keyword', 'describe', 'content', 'pc_preview_count', 'mobile_preview_count', 'add_time'])
                  ->andWhere('state = 3 and {{%content}}.display = 2')
                  ->joinWith('category')
                  ->offset($pageSize*($currPage-1))->limit($pageSize)
                  ->orderBy($sort)
                  // ->createCommand()->getRawSql();
                  ->asArray()->all();
        }
        // P($contentList);
        $contentIds = [];//用来取属性值的
        foreach($contentList as $k => $v){
            $contentList[$k]['preview'] = explode(',', $contentList[$k]['preview']);
            $contentList[$k]['target'] = ($contentList[$k]['url_target'] == 2 and $contentList[$k]['outside'] == 2)?'_blank':'_self';
            $contentList[$k]['content'] = Html::decode($contentList[$k]['content']);
            if($v['outside'] == 1){//站内链接
                $contentList[$k]['url'] = '/' . $v['category']['alias'] . '/article/' . $v['content_id'];
            }else if($v['outside'] == 2){//站外链接
                $contentList[$k]['url'] = $v['outside_url'];
            }
            unset($contentList[$k]['outside']);
            unset($contentList[$k]['outside_url']);
            unset($contentList[$k]['category']);
            unset($contentList[$k]['url_target']);
            array_push($contentIds, $v['content_id']);
        }



        /*获取自定义字段*/
        $contentAttrRelationships = ContentAttrRelationships::find()
                    ->select('content_id, {{%content_attr_relationships}}.attr_id, {{%content_attr_relationships}}.attr_value')
                    ->joinWith('attrName')
                    ->where('{{%content_attr_relationships}}.app_id = :app_id', [':app_id' => $app_id])
                    ->andWhere(['in', 'content_id', $contentIds])
                    ->asArray()->all();
        foreach($contentAttrRelationships as $k => $v){
            /*多选的，需要转成数组*/
            if($v['attrName']['attr_type'] == 2 or $v['attrName']['attr_type'] == 4 or $v['attrName']['attr_type'] == 7){
                $contentAttrRelationships[$k]['attr_value'] = json_decode($v['attr_value']);
            }
            /*编辑器，需要转义*/
            if($v['attrName']['attr_type'] == 6){
                $contentAttrRelationships[$k]['attr_value'] = Html::decode($contentAttrRelationships[$k]['attr_value']);
            }
        }
        // P($contentIds);
        // P($contentAttrRelationships, false);



        /*再次循环 $contentList 把自定义属性放进去*/
        foreach($contentList as $k => $v){
            $tmp = array();
            foreach($contentAttrRelationships as $k1 => $v1){
                if($v['content_id'] == $v1['content_id']){
                    array_push($tmp, array(
                        'attr_name' => $v1['attrName']['attr_name'],
                        'attr_value' => $v1['attr_value']
                    ));
                    $contentList[$k]['attr'] = $tmp;
                }
            }
        }



    }
    // P($contentList[0]['attr'][0]['attr_value'], false);
    // P($contentList);

    $pages = new Pages($count, $pageSize);
    // P($pages->fpage());

    $pageInfo = array(
        'count' => intval($count),
        'currPage' => $currPage,
        'pageSize' => $pageSize,
        'html' => $pages->fpage(isset($params['pageArgs'])?$params['pageArgs']:[0,1,2,3,4,5,6,7,8]),
    );
    
    
    $template->assign("list", $contentList);
    $template->assign("pageInfo", $pageInfo);
    return $content;

}